import sys
sys.path.append('../')



class JT808util(object):

	'''
	多用途的公共工具类 - util
	'''

	@classmethod
	def check_code(msg):
		
		''' 
		接收原始数据后计算返回 byte校验码, msg 必须是python字节码流 ，不能是十六进制的ascii，如 7e
		@param: msg b'~\x80\x01\x00\x05\x06H84!4\x00\x00\x00\x00\x01\x02\x00\xd0~' --> 校验码：$
		'''
		
		ascii_data = msg[1:-2]
		m_len = len(ascii_data)
		tmp_check = 0
		for t in range(m_len):
			tmp_check ^= ascii_data[t]

		pack_tmp_check = struct.pack('>B', tmp_check)
		return pack_tmp_check


	@classmethod
	def bcd2str(bcdarray):

		'''
		将bcdarray 解码成12位SIM字符串
		'''
		
		return ( ''.join(['%02x'% c for c in bcdarray]) ).strip('0')	#去掉开头结尾字符 0


	@classmethod
	def str2bcd(number):

		'''
		将number编码成6个10进制数字，返回列表
		'''
		
		numtest = '%012d'% int(number)
		return [(ord(numtest[x])-ord('0'))<<4 | (ord(numtest[x+1])-ord('0')) for x in range(0, len(numtest), 2)]


	@classmethod
	def make_auth():

		'''
		随机生成8位鉴权码，返回数字列表
		'''

		result_list = []
		for i in range(0,8):
			temp = random.randint(1, 9)
			result_list.append(ord(str(temp)))

		return result_list


	def to_datetime(strx=''):

		'''
		@param: time_str = '190726143544'
		'''

		date = strx[0:6]  # Example '190726'
		the_time = strx[6:12]  # Example '144515'
		sub_date = '20'
		sub_time = ' '

		for x in range(0, len(date), 2):
			sub_date += date[x:x+2] +'-'

		for x in range(0, len(the_time), 2):
			sub_time += the_time[x:x+2] +':'

		datetime = sub_date.rstrip('-') + sub_time.rstrip(':')	# sub_time = ' 11:40:19'
		
		return to_datetime	# datetime = 2016-1-5 11:40:19'



		@classmethod
		def send_7e7d(bin_str):

			'''
			发送data前转义
			'''
			

			rst = bin_str.replace(b'}', b'}\x02')
			rst = rst.replace(b'~', b'}\x02')

			return rst


		@classmethod
		def recv_7e7d(bin_str):

			'''
			接收data后转义
			'''
			
			rst = bin_str.replace( b'}\x02',  b'}')
			rst = rst.replace(b'}\x02', b'~')

			return rst